package sqlClass.appClass;

import general.appClass.SystemInfo;
import general.dbClass.DBCategory;
import general.dbClass.DBKeyword;
import general.dbClass.DBPicInfo;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import sqlClass.daoClass.DaoUpdate;

/**
 * Servlet implementation class BildUpApp
 */
@WebServlet("/UpdateApp")
public class UpdateApp extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static long uploadTime;
	public static long uploadSize;
	public static int uploadCount;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateApp() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SystemInfo.init(request);

		response.setContentType("text/html; charset=UTF-8");
		// PrintWriter out = response.getWriter();

		// System Information Manage Class
		Connection conn = SystemInfo.getConn(request);

		String action = request.getParameter("action");
		if (action != null && action.equals("uploadImage")) {
			String type = request.getParameter("type");
			if (type != null && type.equals("single")) {
				this.insertSingleImg(request, response);
			} else {
				this.insertMultiImg(request, response);
			}

		}

		//System.out.println(action);
		if (action != null && action.equals("insertCategory")) {
			this.insertCategory(conn, request, response);
		}
		if (action != null && action.equals("insertKeyword")) {
			this.insertKeyword(conn, request, response);
		}
		if (action != null && action.equals("modifyCategory")) {
			this.modifyCategory(conn, request, response);
		}
		if (action != null && action.equals("modifyKeyword")) {
			this.modifyKeyword(conn, request, response);
		}
		if (action != null && action.equals("deleteCategory")) {
			this.deleteCategory(conn, request, response);
		}
		if (action != null && action.equals("deleteKeyword")) {
			this.deleteKeyword(conn, request, response);
		}
	}

	private void insertCategory(Connection conn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("category");

		try {
			DaoUpdate.insertCategory(conn, name);

			String url = response
					.encodeURL("/sqlSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void modifyCategory(Connection conn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("nr"));
		String value = request.getParameter("value");
		try {
			DaoUpdate.modifyCategory(conn, nr, value);
	
			String url = response
					.encodeURL("/sqlSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void deleteCategory(Connection conn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		int nr = Integer.parseInt(request.getParameter("nr"));
		try {
			DaoUpdate.deleteCategory(conn, nr);
			String url = response
					.encodeURL("/sqlSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}
	
	
	private void insertKeyword(Connection conn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String word = request.getParameter("word");
		try {
			DaoUpdate.insertKeyword(conn, word);

			String url = response
					.encodeURL("/sqlSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}
	
	private void modifyKeyword(Connection conn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("nr"));
		String value = request.getParameter("value");
		try {
			DaoUpdate.modifyKeyword(conn, nr, value);

			String url = response
					.encodeURL("/sqlSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void deleteKeyword(Connection conn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		int nr = Integer.parseInt(request.getParameter("nr"));
		try {
			DaoUpdate.deleteKeyword(conn, nr);
			String url = response
					.encodeURL("/sqlSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}
	
	
	@SuppressWarnings("rawtypes")
	private void insertSingleImg(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		DBPicInfo picInfo = new DBPicInfo();

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);

			if (!ServletFileUpload.isMultipartContent(request)) {
				System.out.println("sorry. No file gefound");
				return;
			}
			// parse request
			List items = sfu.parseRequest(request);
			FileItem file = null;
			int lock = 1;
			ArrayList<DBCategory> categories = new ArrayList<DBCategory>();
			ArrayList<DBKeyword> keywords = new ArrayList<DBKeyword>();

			Iterator iter = items.iterator();

			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();

				if (item.isFormField()) {
					if (item.getFieldName().equals("imgName")) {
						if (item.getString().equals("")) {
							picInfo.setName(file.getName());
						} else {
							picInfo.setName(item.getString());
						}

					}

					if (item.getFieldName().equals("imgRate")) {
						if (item.getString().equals("")) {
							picInfo.setRate(0);
						} else {
							picInfo.setRate(Integer.parseInt(item.getString()));
						}

					}

					if (item.getFieldName().equals("frei")
							&& item.getString().equals("freigegeben")) {
						lock = 0;
					}

					if (item.getFieldName().equals("categorie")) {

						DBCategory tmp = new DBCategory(Integer.parseInt(item
								.getString()), null);
						categories.add(tmp);
					}

					if (item.getFieldName().equals("keywords")) {
						String keywordsInput = item.getString();
						String delims = ",";
						String[] tmp = keywordsInput.split(delims);
						for (int i = 0; i < tmp.length; i++) {
							if (tmp[i].equals(""))
								break;
							DBKeyword keyword = new DBKeyword(
									Integer.parseInt(tmp[i]), null);
							keywords.add(keyword);
						}
					}
				} else {
					file = item;
				}
			}
			String fileName = file.getName();
			if (checkFileType(fileName)) {
				picInfo.setCategories(categories);
				picInfo.setKeywords(keywords);

				InputStream fin = file.getInputStream();
				DaoUpdate
						.insertPic(SystemInfo.getSqlConn(), picInfo, lock, fin);
				request.setAttribute("msg", "Insert Picture successfully!");
				String url = response.encodeURL("/successful.jsp");
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher(url);
				dispatcher.forward(request, response);
			} else {
				throw new Exception("File type is Wrong!");
			}

		} catch (Exception e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	@SuppressWarnings("rawtypes")
	private void insertMultiImg(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ArrayList<DBPicInfo> picInfoList = new ArrayList<DBPicInfo>();
		ArrayList<FileItem> fileItemList = new ArrayList<FileItem>();
		int count = 0;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);

			if (!ServletFileUpload.isMultipartContent(request)) {
				System.out.println("sorry. No file gefound");
				return;
			}
			// parse request
			List items = sfu.parseRequest(request);
			FileItem file = null;
			int lock = 1;
			ArrayList<DBCategory> categories = new ArrayList<DBCategory>();
			ArrayList<DBKeyword> keywords = new ArrayList<DBKeyword>();
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();

				if (!item.isFormField()) {
					file = item;
					String fileName = file.getName();
					if (checkFileType(fileName)) {
						fileItemList.add(file);
						DBPicInfo picInfo = new DBPicInfo();
						picInfo.setName(fileName);
						picInfo.setRate(0);
						picInfo.setCategories(categories);
						picInfo.setKeywords(keywords);
						picInfoList.add(picInfo);
					}

				}
			}
			for (int i = 0; i < fileItemList.size(); i++) {
				InputStream fin = fileItemList.get(i).getInputStream();
				System.out.println("uploading:pic" + i);
				DaoUpdate.insertPic(SystemInfo.getSqlConn(),
						picInfoList.get(i), lock, fin);
				count++;
			}
			if (count == 0) {
				String url = response.encodeURL("/errorInfo.jsp");
				request.setAttribute("Error", "Kein Photo ist hohegeladen!");
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher(url);
				dispatcher.forward(request, response);
			} else {
				String url = response.encodeURL("/successful.jsp");
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher(url);
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private static boolean checkFileType(String fileName) {
		if (fileName.indexOf(".") > 0) {
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			if (fileType.equalsIgnoreCase(".jpg")
					|| fileType.equalsIgnoreCase(".jpeg")) {
				return true;
			}
		}
		return false;
	}
}
